package com.ryzx.log.collector;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.mongodb.BasicDBObject;
import com.ryzx.common.status.ServiceRunStatus;
import com.ryzx.common.util.IPUtil;
import com.ryzx.common.util.JsonUtil;
import com.ryzx.common.util.SpringUtil;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MongoDBAppender  extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
    private static final Calendar calle = Calendar.getInstance();
    @Override
    protected void append(ILoggingEvent eventObject) {
        if(ServiceRunStatus.isRun()) {
            MongoTemplate mongoTemplate = SpringUtil.getBean(MongoTemplate.class);
            final BasicDBObject doc = new BasicDBObject();

            String loggerName = eventObject.getLoggerName();
            if (loggerName.contains("ControllerLogHandler") ||loggerName.contains("ServiceLogHandler") ) {
                LogCollectorEntity entity=JsonUtil.String2obj(eventObject.getFormattedMessage(), LogCollectorEntity.class);
                doc.append("response", entity.getResponse());
                doc.append("param", entity.getParam());
                doc.append("handleClass", entity.getHandleClass());
                doc.append("url", entity.getUrl());
                doc.append("costTime", entity.getCostTime());
                doc.append("method", entity.getMethod());
                doc.append("handleMethod", entity.getHandleMethod());
                doc.append("traceId", entity.getTraceId());
                doc.append("timeLevel", entity.getTimeLevel());
                doc.append("stackTrace", entity.getStackTrace());
            } else {
                doc.append("message", eventObject.getFormattedMessage());
            }
            calle.setTime(new Date());
            calle.add(Calendar.HOUR_OF_DAY, +8);
            doc.append("time", calle.getTime());
            doc.append("level", eventObject.getLevel().toString());
            doc.append("loggerName", loggerName);
            doc.append("ip", IPUtil.getIpAddress());
            mongoTemplate.insert(doc, "logTable");
        }
    }
}